/*The MIT License

Copyright (c) <1/27/2011> <erick.difiore>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

package com.d4a5.mapping.google
{
	import com.d4a5.mapping.core.AmfObject;
	import com.d4a5.mapping.core.Bounds;
	import com.d4a5.mapping.core.IAmfObject;
	import com.d4a5.mapping.core.IHighlightedObject;
	import com.d4a5.mapping.core.ISelectedObject;
	import com.d4a5.mapping.core.MinMax;
	import com.google.maps.LatLng;
	import com.google.maps.LatLngBounds;
	import com.google.maps.Map;
	import com.google.maps.PaneId;
	import com.google.maps.interfaces.IMap;
	import com.google.maps.interfaces.IPane;
	import com.google.maps.overlays.OverlayBase;
	
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	
	
	public class wmgBaseOverlay extends OverlayBase implements IAmfObject, IHighlightedObject, ISelectedObject
	{
		public static const EVENT_HIGHLIGHT_TRUE:String = "highlight_true";
		public static const EVENT_HIGHLIGHT_FALSE:String = "highlight_false";
		public static const EVENT_SELECT_TRUE:String = "select_true";
		public static const EVENT_SELECT_FALSE:String = "select_false";
				
		public var _highlighted:Boolean = false;
		public var _highlightedChanged:Boolean = false;
		
		public var _selected:Boolean = false;
		public var _selectedChanged:Boolean = false;
		
		protected var _highlightable:Boolean = true;
		protected var _selectable:Boolean = true;
		
		protected var _amf:AmfObject;
		
		protected var _refreshRequested:Boolean = false;
		protected var _refreshPositionRequested:Boolean = false;
		
		protected static var currentZoomLevel:int = -1;
		protected static var currentCenterLatLng:LatLng;
		protected static var currentMatrix:Matrix;
		
		protected static var currentMapBounds:Bounds;
		protected static var currentViewportBounds:Bounds;
		protected static var currentMapLatLngBounds:LatLngBounds;
		
		protected var _drawn:Boolean = false;
		
		public var attributes:Object = new Object();
		
		public var viewportOverlapRatio:Number = 1.5;
		
		
		public function wmgBaseOverlay()
		{
			super();
		}
		
		public function get amf():AmfObject
		{
			return this._amf;
		}
		public function set amf( a:AmfObject ) : void {
			this._amf = a;
			if( this._amf ){
				this.attributes = this._amf.attributes;
			}
		}
		
		override public function getDefaultPane(arg0:IMap):IPane{
			return arg0.getPaneManager().getPaneById(PaneId.PANE_OVERLAYS+1);
		}
		
		public function getLabel( labelField:String = null ):String {
			return ( this.attributes && this.attributes[labelField] ) ? this.attributes[labelField] : super.toString();	
		}
		
		public function get highlighted() : Boolean {
			return this._highlighted;
		}
		public function set highlighted( state:Boolean ) : void {
			if( state != this._highlighted && this._highlightable ){
				this._highlightedChanged = true;
				this._highlighted = state;
				this.invalidateProperties();
			}
		}
		
		public function get highlightable() : Boolean {
			return this._highlightable;
		}
		public function set highlightable( state:Boolean ) : void {
			if( state != this._highlightable ){
				this.highlighted = false;
				this._highlightable = state;
			}
		}
		
		
		public function get selected() : Boolean {
			return this._selected;
		}
		public function set selected( state:Boolean ) : void {
			if( state != this._selected && this._selectable ){
				this._selectedChanged = true;
				this._selected = state;
				this.invalidateProperties();
			}
		}
		
		public function get selectable() : Boolean {
			return this._selectable;
		}
		public function set selectable( state:Boolean ) : void {
			if( state != this._selectable ){
				this.selected = false;
				this._selectable = state;
			}
		}
		
		
		override protected function commitProperties() : void {
			var refresh:Boolean = false;
			var eventType:String;
			
			if( this._highlightedChanged ){
				this._highlightedChanged = false;
				eventType = ( this._highlighted ) ? EVENT_HIGHLIGHT_TRUE : EVENT_HIGHLIGHT_FALSE;
				this.dispatchEvent( new Event( eventType ) );
				refresh = true;
			}
			
			if( this._selectedChanged ){
				this._selectedChanged = false;
				eventType = ( this._selected ) ? EVENT_SELECT_TRUE : EVENT_SELECT_FALSE;
				this.dispatchEvent( new Event( eventType ) );
				refresh = true;
			}
			
			if( refresh ){
				this.refresh();
			}
		}
		
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
			super.updateDisplayList( unscaledWidth , unscaledHeight );
			
			if( this._refreshRequested ){
				this._refreshRequested = false;
				
				//wmgBaseOverlay.currentCenterLatLng = null;
				this.positionOverlay( true );
			}
		}
		
		public function refresh() : void {
			this._refreshRequested = true;
			this.invalidateDisplayList();
		}
		
		public static function refreshMatrix() : void {
			wmgBaseOverlay.currentCenterLatLng = null;
		}
		
		public function getMatrix() : Matrix {
			if( this.pane && this.pane.map ){
				var zoom:int = this.pane.map.getZoom();
				var center:LatLng = this.pane.map.getCenter();
				var mapLatLngBounds:LatLngBounds = this.pane.map.getLatLngBounds();
				
				if( zoom != wmgBaseOverlay.currentZoomLevel || center.equals( wmgBaseOverlay.currentCenterLatLng ) == false || mapLatLngBounds.equals( wmgBaseOverlay.currentMapLatLngBounds ) == false  ){
					var viewport:Rectangle = this.pane.getViewportBounds();
					var mapWidthPixels:Number = ( 1 << (zoom + 8) );
					var resolution:Number = 40075016.685578494 / mapWidthPixels;
					
					var UL:Point = this.pane.fromPaneCoordsToProjectionPoint( viewport.topLeft );
					var LR:Point = this.pane.fromPaneCoordsToProjectionPoint( viewport.bottomRight );
					
					mapWidthPixels >>= 1;
					
					var xmin:Number =  resolution * ( viewport.left   + UL.x - mapWidthPixels );
					var xmax:Number =  resolution * ( viewport.right  + UL.x - mapWidthPixels );
					var ymin:Number = -resolution * ( viewport.bottom + UL.y - mapWidthPixels );
					var ymax:Number = -resolution * ( viewport.top    + UL.y - mapWidthPixels );
					
					
					wmgBaseOverlay.currentZoomLevel = zoom;
					wmgBaseOverlay.currentCenterLatLng = center;
					wmgBaseOverlay.currentMapBounds = new Bounds( new MinMax(xmin,xmax) , new MinMax(ymin,ymax) );
					wmgBaseOverlay.currentMatrix = new Matrix( 1/resolution , 0 , 0 , -1/resolution , -UL.x + mapWidthPixels , -UL.y  + mapWidthPixels );
					wmgBaseOverlay.currentMapLatLngBounds = mapLatLngBounds;
					
					wmgBaseOverlay.currentViewportBounds = wmgBaseOverlay.currentMapBounds.applyMatrix( wmgBaseOverlay.currentMatrix );
				}
			}
			return wmgBaseOverlay.currentMatrix;
		} 
		
		public function retrieveOptions() : Object {
			if( this.pane && this.pane.map is wmgMap ){
				var layer:Object = (this.pane.map as wmgMap).getLayerByPane( this.pane );
				if( layer && layer.getOptions is Function ){
					return layer.getOptions( this );
				}
			}
			return null;
		}
		
		protected function draw( m:Matrix ) : void { 
		}
		
		public function get isInView() : Boolean {
			if( this.pane != null && this.pane.map ){
				var mapWidthPixels:Number = ( 1 << (wmgBaseOverlay.currentZoomLevel + 8) );
				return wmgBaseOverlay.currentViewportBounds.overlayedByCheckXWrapping( this._amf.bounds.applyMatrix( wmgBaseOverlay.currentMatrix ) , mapWidthPixels  );
			}
			return false;	
		}
		
		protected function get CurrentMapBounds() : Bounds {
			return wmgBaseOverlay.currentMapBounds;
		}
		
		override public function positionOverlay(arg0:Boolean):void {
			if( this.pane != null ){
				var m:Matrix = this.getMatrix();
				if( m ){
					
					if( this._amf ){
						if( arg0 || this._drawn == false){
							this.draw( m );
						}
						
						var mapWidthPixels:Number = ( 1 << (wmgBaseOverlay.currentZoomLevel + 8) );
						
						this.y = m.ty;
						this.x =(this._amf.bounds.x.min > this.CurrentMapBounds.x.max) 
							? m.tx - mapWidthPixels
							: ( this._amf.bounds.x.max < this.CurrentMapBounds.x.min )
							? m.tx + mapWidthPixels
							: m.tx;					
						
					}
					else{
						this._drawn = false;
						this.graphics.clear();
					}
				}
			}
		}
		
		
		
	}
}